<?php

namespace app\admin\model;

use app\model\Model;

class Link extends Model
{
  public $privilege = 'link';
  public $cids;
  public $id;
  public $res;
  public $db;

  function __construct()
  {
    include 'check.php';
    new Check();

    $this->db = $GLOBALS['db'];
    $this->cids = checkAdminPriv(@$this->privilege); // 判断权限
    $this->id = intval($_GET['id']);
    $this->res = array_sort(file_get('json', 'link'), 'l_order');
  }

  function index()
  {
    include_once LIB_PATH . 'cls.page.php';
    $this->tpl('link', [
      'list' => $this->res,
      'db' => $this->db
    ]);
  }

  function add()
  {
    $data = get_post(['l_picture']);

    $this->res[] = $data;
    $this->res = array_sort($this->res, 'l_order');

    if (file_it(json_encode($this->res, 320), 'json', 'link')) {
      admin_log('链接新增');
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'link'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
    /*
    $data['l_name'] = str_safe($_POST['l_name']);
    $data['l_picture'] = str_safe($_POST['l_picture']);
    $data['l_link'] = str_safe($_POST['l_link']);
    $data['l_order'] = intval($_POST['l_order']);

    if (is_array($this->res)) {
      $this->res[] = $data;
    } else {
      $this->res = array(0 => $data);
    }
    */
  }

  function edit()
  {
    $this->tpl('link_edit', [
      'row' => $this->res[$this->id],
      'db' => $this->db
    ]);
  }

  function edit_action()
  {
    $data = get_post(['l_picture']);
    $this->res[$this->id] = $data;
    $this->res = array_sort($this->res, 'l_order');

    if (file_it(json_encode($this->res, 320), 'json', 'link')) {
      admin_log('链接编辑 [' . $this->id . ']');
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'link'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
    /*
    null_back($_POST['l_name'], '请填写链接名称');
    non_numeric_back($_POST['l_order'], '排序必须是数字!');

    $data['l_name'] = str_safe($_POST['l_name']);
    $data['l_picture'] = str_safe($_POST['l_picture']);
    $data['l_link'] = str_safe($_POST['l_link']);
    $data['l_order'] = intval($_POST['l_order']);
    */
  }

  function del()
  {
    unset($this->res[$this->id]);
    $this->res = array_sort($this->res, 'l_order');

    if (file_it(json_encode($this->res, 320), 'json', 'link')) {
      admin_log('链接删除 [' . $this->id . ']');
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'link'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
  }

  function __destruct()
  {
  }
}